//
//  KYOAuthViewController.swift
//  01-我的微博
//
//  Created by apple on 15/7/30.
//  Copyright © 2015年 KY. All rights reserved.
//

import UIKit
import SVProgressHUD

class KYOAuthViewController: UIViewController, UIWebViewDelegate{
    
    // 搭建界面
    private lazy var webView = UIWebView ()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 加载授权界面
        webView.loadRequest(NSURLRequest(URL: KYNetworkTools.sharedNetworkTools.oauthURL))
    }
    
    override func loadView() {
        view = webView
        webView.delegate = self
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "closeOAuth")
    }
    
    /// 关闭网页
    func closeOAuth() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 网页开始加载
    func webViewDidStartLoad(webView: UIWebView){
        SVProgressHUD.show()
    }
    
    /// 网页加载完毕
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    /// 1. 如果请求的 URL 包含 回调地址，需要判断参数，否则继续加载
    ///2. 如果请求参数中，包含 code，可以从请求的 url 中获得请求码
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        
        let urlString = request.URL?.absoluteString
        // 判断请求是否包含回调地址
        if !urlString!.hasPrefix(KYNetworkTools.sharedNetworkTools.redirectUri){
            return true
        }
        
        // 判断
        if let query = request.URL?.query where query.hasPrefix("code="){
            
            let code = query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
        
            
            loadAccessToken(code)
        }
        else {
            closeOAuth()
        }
        return false
    }
    
    /// 加载token
    private func loadAccessToken(code: String) {
        
        KYNetworkTools.sharedNetworkTools.loadAccessToken(code) { (result, error) -> () in
            if error != nil || result == nil {
                self.netError()
                return
            }
            // 字典转模型
            // 1.用 Token 获取的信息创建账户模型
            // 2.异步加载用户信息
            // 3.保存用户信息(模型中完成)
            KYUserAccountModel(dict: result!).loadUserInfo({ (error) -> () in
                if error != nil {
                    self.netError()
                    return
                }
                
                NSNotificationCenter.defaultCenter().postNotificationName(KYRootViewControllerSwitchNotification, object: false)
                self.closeOAuth()
            })
        }
    }
    
    /// 网络出错处理
    private func netError() {
        SVProgressHUD.showInfoWithStatus("您的网络不给力")
        
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
        
        // 延时一段时间在关闭  此处最后修改了
        dispatch_after(when, dispatch_get_main_queue()) {
            
            self.closeOAuth()
        }
        
        
    }
}
